import { constantRoutes, asyncRoutes } from '@/router';
import { defineStore } from 'pinia';
// import { useProductStore } from '@/stores/product'

export const usePermissionStore = defineStore('permission', {
    state: () => ({
        accessedRoutes: [],
        routes: [] as any
    }),
    actions: {
        getRoutes(){
            const role = '1'
            let route = [] as any
            if(role == '1' || role =='2'){
                route = constantRoutes
            }else if(role == '3'){
                route = constantRoutes.filter((item:any)=>{
                    if(item.children){
                        item.children = item.children.filter((children:any) => {
                            console.log(children)
                            return !children.meta || !children.meta.roleBan || !children.meta.roleBan.includes(3)
                        })
                    }
                    return item.path != '/team'
                })
            }else if(role == '4'){
                constantRoutes.forEach((item:any) =>{
                    if(item.path == '/login' || item.path == '/'){
                        route.push(item)
                    }else if(item.path != '/team'){
                        if(item.children){
                            item.children = item.children.filter((children:any) => {
                                return []
                            })
                            if(item.children.length == 0){
                                item.del = true
                            }
                        }
                    }
                })
                route = constantRoutes.filter((item:any) => {
                    return item.del != true && item.path != '/team'
                })
            }
            this.routes = route
        },

        hasPermission(roles: string[], route: any) {
            if (route.meta && route.meta.roles) {
                return roles.some((role: any) => route.meta.roles.includes(role))
            } else {
                return true
            }
        },

        filterAsyncRoutes(routes: any, roles: string[]) {
            const res: any = []
            routes.forEach((route: any) => {
                const tmp = { ...route }
                if (this.hasPermission(roles, tmp)) {
                    if (tmp.children) {
                        tmp.children = this.filterAsyncRoutes(tmp.children, roles)
                    }
                    res.push(tmp)
                }
            })
            return res
        },


        generateRoutes(roles: string[]) {
            if (roles.includes('admin')) {
                this.accessedRoutes = asyncRoutes as any || []
            } else {
                this.accessedRoutes = this.filterAsyncRoutes(asyncRoutes, roles)
            }
            return this.accessedRoutes
        }
    }
})